package cn.tworice.backup.scheduler;

import cn.tworice.backup.executor.DatabaseParam;
import cn.tworice.backup.service.BackupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.ScheduledFuture;

@Service
@Slf4j
public class BackupScheduledTask {

    @Resource
    private ThreadPoolTaskScheduler backupTaskScheduler;

    ScheduledFuture<?> scheduledFuture;

    @Resource
    private BackupService backupService;

    public void scheduleTask(DatabaseParam param,Trigger trigger) {
        Runnable task = () -> {
            log.info("开始执行定时备份数据库任务");
            backupService.backup(param);
        };
        // 将之前的备份任务停止掉，后面有需要可以设置多个备份任务
        if(scheduledFuture != null && !scheduledFuture.isDone()){
            this.scheduledFuture.cancel(true);
        }
        this.scheduledFuture = this.backupTaskScheduler.schedule(task, trigger);
    }


}
